/*
 * @Author: Rays77
 * @Date: 2022-10-21 09:18:13
 * @LastEditors: Rays77
 * @LastEditTime: 2022-10-21 11:20:43
 * @Description:
 * @FilePath: \shop-admin\src\api\file.ts
 */
import { request } from '@/utils/request'
import { Upload } from '../interface/index'
import { AxiosProgressEvent } from 'axios'

export class fileService {
  // 单个文件上传
  static uploadFile = (data: { requestId: number; file: File }) => {
    const fd = new FormData()
    fd.append('pid', data.requestId.toString())
    fd.append('file', data.file)
    return request<{
      list: Upload.FileCategory[]
    }>({
      method: 'POST',
      url: '/api/upload',
      data: fd,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
  }

  // 文件分片上传
  static uploadFileByFormData = (
    formData: FormData,
    callback: (progressEvent: AxiosProgressEvent) => void,
  ) => {
    return request({
      method: 'post',
      url: '/upload',
      data: formData,
      params: {
        chunk: formData.get('hash'),
      },
      headers: {
        'Content-Type': 'multipart/form-data;charset=utf-8',
      },
      // 上传进度条处理  loaded: 已上传文件大小 /  total: 被上传文件的总大小
      onUploadProgress: (progressEvent) => {
        // 原生获取上传进度事件
        if (progressEvent.lengthComputable) {
          callback && callback(progressEvent)
        }
        // console.log('loaded:', progressEvent.loaded)
        // console.log('total:', progressEvent.total)
        // const result = parseInt((progressEvent.loaded / progressEvent.total).toFixed(2))
        // console.log('文件上传进度百分比:', (result * 100 + '%'))
      },
    })
  }

  // 合并文件分片
  static mergeFileChunks = function (data: { filename: string; size: number }) {
    return request({
      url: '/merge',
      method: 'post',
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
      },
      data: JSON.stringify({
        size: data.size,
        fileName: data.filename,
      }),
    })
  }

  /**
   * 文件秒传,所谓的文件秒传，即在服务端已经存在了上传的资源，所以当用户再次上传时会直接提示上传成功
  文件秒传需要依赖上一步生成的 hash，即在上传前，先计算出文件 hash，并把 hash 发送给服务端进行验证，由于 hash 的唯一性，所以一旦服务端能找到 hash 相同的文件，则直接返回上传成功的信息即可
   * @param filename 文件名
   * @param fileHash 文件分片hash值
   */
  static verifyUploaded = async function (filename: string, fileHash: string) {
    const { data } = await request({
      url: '/verify',
      method: 'post',
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
      },
      data: JSON.stringify({
        filename,
        fileHash,
      }),
    })
    return JSON.parse(data)
  }
}
